//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
		report_img: '',
		id: ''
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },

	// 统计数据的事件
	logvisit: function () {
		wx.request({
			url: app.globalData.baseurl + '/API/skin/log_visit',
			method: 'GET',
			data: {
				openid: this.data.id,
				pageid: 1,
				content: ''
			},
			success: function (res) {
				console.log(res)
			}
		})
	},
	

  onLoad: function() {
		var that = this
    wx.setNavigationBarTitle({
      title: '芙兰玉肌肤测试'
    })
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          //   this.setData({
          //     userInfo: res.userInfo,
          //     hasUserInfo: true
          //   })
        }
      })
    }
		wx.getStorage({
			key: "userinfo",
			success: function (res) {
				console.log(res)
				if (res) {
					that.setData({
						id: res.data.openid
					})
					that.logvisit();
				}
			}
		})
  },
	// 授权的方法
  getUserInfo(e, jumpUrl) {
		var that = this
		if (e.detail.errMsg == "getUserInfo:fail auth deny") {
			//不同意授权
			return false;
		}
		var encryptedData = e.detail.encryptedData;
		var iv = e.detail.iv;
		var signature = e.detail.signature;
		var rawData = e.detail.rawData;
		// 用户登录
		wx.login({
			success: res => {
				// 发送 res.code 到后台换取 openId, sessionKey, unionId
				if (res.code) {
					console.log(res);
					wx.request({
						url: app.globalData.baseurl + '/api/user/get_openid',
						method: 'POST',
						data: {
							code: res.code,
							encryptedData: encryptedData,
							signature: signature,
							rawData: rawData,
							iv: iv,
						},
						success: function (res) {
							console.log(res);
							if (res.data.status == 1) {
								console.log(res.data.userinfo)
								that.setData({
									id: res.data.userinfo.openid
								})
								// 统计数据
								that.logvisit();
								app.globalData.userInfo = res.data.userinfo
								wx.setStorage({
									key: "userinfo",
									data: res.data.userinfo,
									success: function () {
										// 如果是点击拍照的话，则进入选择图片功能
										if (jumpUrl === 'choseImg') {
											that.choseImage()
										} else {
											// 否则跳转档案列表
											wx.navigateTo({
												url: jumpUrl
											})
										}
									}
								})
							}
						}
					})
				} else {
					console.log('登录失败');
				}
			}
		})
		// app.globalData.userInfo = e.detail.userInfo
  },
	// 点击拍照
  takePhoto(e) {
		// 如果没有授权则调用授权的方法
		if(!app.globalData.userInfo || this.data.id === ''){
			this.getUserInfo(e, 'choseImg')
		}else(
			// 否则进入选择照片功能
			
			this.choseImage()
		)
		console.log(app.globalData.userInfo)
  },
	choseImage(){
		var that = this
		wx.chooseImage({
			count: 1, // 默认9
			sizeType: 'compressed', // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
			success: function (res) {
				// 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
				var tempFilePaths = res.tempFilePaths
				wx.uploadFile({
					url: app.globalData.baseurl + '/api/uploads/upload/name/img', //仅为示例，非真实的接口地址
					filePath: tempFilePaths[0],
					name: 'img',
					success: function (res) {
						var data = JSON.parse(res.data)
						that.setData({
							report_img: data.url
						})
						that.uploadTakePhotoMsg(res)
						//do something
					}
				})
			}
		})
	},
	uploadTakePhotoMsg() {
		var id = ''
		var that = this
		var timestamp = Date.parse(new Date()) / 1000;
		var data = {
			report_time: timestamp,
			openid: that.data.id,
			report_img: that.data.report_img
		}
		wx.showToast({
			title: '上传中！',
			icon: 'loading',
			duration: 2000
		})
		wx.request({
			url: app.globalData.baseurl + '/api/fans/faceonly',
			method: 'POST',
			data: {
				image: app.globalData.baseurl + that.data.report_img,
				imagetype: 'URL'
			},
			success: function (res) {
				if (res.data.error_code === 0) {
					wx.request({
						url: app.globalData.baseurl + '/api/user/saveReport',
						method: 'POST',
						data: data,
						success: function (res) {
							console.log(res)
							wx.showToast({
								title: '提交成功！',
								icon: 'success',
								duration: 1000
							})
							// 将提交的信息保存到缓存中
							try {
								wx.setStorageSync('report', that.data.report_img)
							} catch (e) { }
							setTimeout(function () {
								wx.navigateTo({
									url: '../sure/sure'
								})
							}, 1000)
						}
					})
				} else {
					wx.request({
						url: app.globalData.baseurl + '/api/user/saveReport',
						method: 'POST',
						data: data,
						success: function (res) {
							console.log(res)
						}
					})
					wx.showToast({
						title: '提交失败或未识别到人脸，请重新拍照！',
						icon: 'none',
						duration: 2000
					})
				}
			}
		})
	},
  handleClickRecord(e) {
		// 如果没有授权则调用授权的方法
		if (!app.globalData.userInfo || this.data.id === '') {
			this.getUserInfo(e, '../record/record')
		} else (
			// 否则跳转档案列表页
			wx.navigateTo({
				url: '../record/record'
			})
		)
		console.log(app.globalData.userInfo)
    // app.globalData.userInfo = e.detail.userInfo
  }
})